package controller;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import model.Zimmer;

import view.CreateRoomView;

public class GUICreateRoomViewController extends GUIAbstractController implements ActionListener
{
	private CreateRoomView roomView;
	private Zimmer room;

	public GUICreateRoomViewController()
	{
		super();
		
		this.roomView= new CreateRoomView();
		this.roomView.addActionsListeners(this);
	}
	
	public GUICreateRoomViewController(Zimmer roomToEdit){
		this();
		room = roomToEdit;
		updateGuiFieldsFromRoom();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == this.roomView.getBtnCancel()){
			System.out.println("Cancel Button");
			this.roomView.setVisible(false);
			
		}else if(e.getSource()==this.roomView.getBtnSave()){
			System.out.println("Save Button");
			updateRoomFromGuiFields();
			saveOrUpdateRoom();
			this.roomView.setVisible(false);
		}
	}

	private void saveOrUpdateRoom()
	{
		if(room.getId() > 0){
			// update
			super.dbController.updateEntity(room);
		}
		else{
			// insert new
			super.dbController.saveEntity(room);
		}
	}

	public CreateRoomView getRoomView()
	{
		return roomView;
	}
	
	private void updateRoomFromGuiFields(){
		
		if(room == null){
			room = new Zimmer();
		}
		
		room.setName(roomView.getTxtName().getText());
		room.setMaxBelegung(TextFieldParsingHelper.parseIntFromTextField(roomView.getTxtMaxPers()));
		room.setPreisEZ(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice1Pers()));
		room.setPreisDZ(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice2Pers()));
		room.setPreisDreifachbelegung(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice3Pers()));
		room.setPreisEZmitKind(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice1Pers1Child()));
		room.setPreisEZmitZweiKindern(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice1Pers2Children()));
		room.setDZMitKind(TextFieldParsingHelper.parseDoubleFromTextField(roomView.getTxtPrice1Pers2Children()));
	}
	
	private void updateGuiFieldsFromRoom(){
		roomView.getTxtName().setText(room.getName());
		roomView.getTxtMaxPers().setText(""+room.getMaxBelegung());
		roomView.getTxtPrice1Pers().setText(""+room.getPreisEZ());
		roomView.getTxtPrice2Pers().setText(""+room.getPreisDZ());
		roomView.getTxtPrice3Pers().setText(""+room.getPreisDreifachbelegung());
		roomView.getTxtPrice1Pers1Child().setText(""+room.getPreisEZmitKind());
		roomView.getTxtPrice1Pers2Children().setText(""+room.getPreisEZmitZweiKindern());
		roomView.getTxtPrice2Pers1Child().setText(""+room.getDZMitKind());
	}
	

}
